package fr.esiea.es_inf5042.persistance.dao.SQLiteDAO;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import fr.esiea.es_inf5042.utils.SQLScriptParser;
import android.content.Context;
import android.content.res.AssetManager;

import android.database.sqlite.*;

public class SQLiteFactoryOpenHelper extends SQLiteOpenHelper {
	
	private Context context;
	private SQLiteDatabase database;		

	protected SQLiteFactoryOpenHelper(Context context)
	{
		super(context, "SQLiteEmbeddedDataBase", null, 3);		
		
		this.context = context;
		
		database = getWritableDatabase();		
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		
		AssetManager assetManager = null;
		List<String> statements = null;
		Iterator<String> it = null;
		String statement = null;			
		
		this.database = db;
		
		try {
			
			assetManager = context.getAssets();		
			statements = SQLScriptParser.parse(assetManager.open("sql/schema.sql"), context.getCacheDir());
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		it = statements.iterator();
		while(it.hasNext())
		{
			statement = it.next();
			database.execSQL(statement);
		}
			
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		
					
	}
	
	public SQLiteDatabase getDatabase() {
		return database;
	}
}
